package com.apes.scm.masterdata.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Category;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ServeCategory;
import com.apes.scm.masterdata.product.model.StarProduct;
import com.apes.scm.masterdata.product.repository.*;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 功能：商品信息 Service
 *
 * @author HuJianlin
 * @create 2018-03-15 14:35
 */
@Service("productService")
public class ProductService extends DomainService {

    @Autowired
    ProductRepository productRepository;

    @Autowired
    ProductUomRepository productUomRepository;

    @Autowired
    private StarProductRepository starProductRepository;

    @Autowired
    private OutboxSubscriberService outboxSubscriberService;

    @Autowired
    private CategoryRepository categoryRepository;
    //用于装配图得来源区分
    private String sourceFrom = "servicePlan";

    private  JSONObject belongDept = new JSONObject();
    private  JSONObject saleDept = new JSONObject();
    @Value("${apes.switched:false}")
    private Boolean switched;

    public Product save(SimpleRequest request) {
        Product product = request.getO(Product.class);
        return productRepository.saveAndFlush(product);
    }

    public Object  assemblyDrawingProductPrice(SimpleRequest request) {
        JSONObject condition = request.getJO();
        // 定损
        if(condition.containsKey("custom") && "lossQuotation".equals(condition.getString("custom"))) {
            return invoke("fn.fixedLoss.getPrice", condition);
        } else {
        // 服务
            return invoke("fn.service.getPrise", condition);
        }
    }


    public JSONArray queryProduct(SimpleRequest simpleRequest) {
        JSONArray returnDataArray = new JSONArray();
        JSONObject condition = simpleRequest.getJO();
        if(condition.containsKey("custom")) {
            sourceFrom = condition.getString("custom");
        }
        if (Objects.equals("lossQuotation", sourceFrom)) {
            belongDept = condition.getJSONObject("fixedLossDept");
            saleDept = condition.getJSONObject("getCarDept");
        }else {
            belongDept = condition.getJSONObject("belongDept");
            saleDept =  condition.getJSONObject("saleDept");
        }
        if (Objects.isNull(belongDept) || Objects.isNull(saleDept)) {
            throw new RuntimeException("门店信息不能为空!!!");
        }
        JSONObject customerObj = condition.getJSONObject("customer");
        String vin = condition.getJSONObject("customerCar").getString("vin");
        String jekunModelCode = condition.getJSONObject("customerCar").getString("jekunModelCode");

        JSONArray fittlingArray = condition.getJSONArray("fitting");
        fittlingArray.forEach(item -> {
            JSONObject fitting = (JSONObject) item;
            //商品价格前置
            if (fitting.getString("priceForward")!=null && "1-2-4".contains(fitting.getString("priceForward"))) {
                priceForward(returnDataArray, fitting, condition);
            }
            //匹配商品列表和智能配件列表
            else{
                erectionDrawing(returnDataArray, customerObj, vin, jekunModelCode, fitting);
            }
        });
        return returnDataArray;
    }

    //供应商平台
    public void priceForward(JSONArray returnDataArray, JSONObject fitting, JSONObject condition){
        //价格前置生成商品SKU
        inputProduct(returnDataArray, fitting, condition);

        //三头六臂导入服务方案
        santouInputProduct(returnDataArray, fitting, condition);
    }

    //价格前置生成商品SKU
    private void inputProduct(JSONArray returnDataArray, JSONObject fitting, JSONObject condition) {
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(fitting.getString("product")))return;
        JSONObject categoryJSON = fitting.getJSONObject("category");
        String pjmcId = null;
        String pjmcMc = null;
        if (Objects.nonNull(categoryJSON)) {
            pjmcId = categoryJSON.getString("id");
            pjmcMc = categoryJSON.getString("name");
        }else {
            Category category = categoryRepository.findOne("013951");
            pjmcId = category.getId();
            pjmcMc = category.getName();
        }
        Category category = categoryRepository.findOne(categoryJSON.getString("id"));
        if (Objects.nonNull(category)) {
            JSONObject productInfo = new JSONObject();
            productInfo.put("SPMC", fitting.getString("name"));
            if (category == null || category.getClassify() == null) {
                throw new RuntimeException(pjmcMc + " 配件未找到对应品类！请联系数据中心定义");
            }
            productInfo.put("PLID", category.getClassify().getId());
            productInfo.put("PLMC", category.getClassify().getName());
            productInfo.put("PJMCID", pjmcId);
            productInfo.put("PJMC", pjmcMc);
            String productId = generateProduct(productInfo, fitting.getString("partCode"), fitting.getJSONObject("spProduct"));
            if (!StringUtils.isEmpty(productId)){
                Product product = productRepository.findOne(productId);
                fitting.put("product", product);
                fitting.put("uom", product.getUom());
                fitting.remove("partCode");
                condition.put("servicePlanItem", fitting);
                JSONObject result = invoke("fn.priceForwardService.onceAgainPrice", condition);
                returnDataArray.add(result);
            }
        } else {
            throw new RuntimeException("[" +pjmcId+ "]" + pjmcId + ", 此配件没有维护对应品类, 请先维护配件的品类再选择该配件");
        }
    }

    //三头六臂导入服务方案,三头六臂的商品有对应关系不用重复生成商品
    private void santouInputProduct(JSONArray returnDataArray, JSONObject fitting, JSONObject condition){
        if (fitting.getString("product") == null || fitting.getString("product").isEmpty() || fitting.get("product") instanceof Product)return;
        Product product = productRepository.findOne(fitting.getString("product"));
        if (Objects.isNull(product)) throw new RuntimeException("系统商品数据维护错误，请联系数据中心修改！");
        fitting.put("product", product);
        fitting.put("uom", product.getUom());
        fitting.remove("partCode");
        condition.put("servicePlanItem", fitting);
        JSONObject result = invoke("fn.priceForwardService.onceAgainPrice", condition);
        returnDataArray.add(result);
    }

    /**
     * ‘匹配商品列表’与‘智能配件列表’，生成商品sku或者匹配商品
     * @param returnDataArray
     * @param customerObj
     * @param vin
     * @param jekunModelCode
     * @param fitting
     */
    private void erectionDrawing(JSONArray returnDataArray, JSONObject customerObj, String vin, String jekunModelCode, JSONObject fitting) {
        boolean isMatchParts = fitting.getBooleanValue("isMatchParts");
        if (!fitting.getBooleanValue("isMatchParts")) {
            fitting.put("oldPartCode", fitting.getString("partCode"));
            fitting.put("partName", "");
            fitting.put("partCode", "");
            returnDataArray.add(fitting);
            return;
        }
        String partName = fitting.getString("partName");
        String partCode = fitting.getString("partCode");
        String regEx = "[\\s~·`!！@#￥$%^……&*（()）\\-——\\-_=+【\\[\\]】｛{}｝\\|、\\\\；;：:‘'“”\"，,《<。.》>、/？?]";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(partCode);
        partCode = matcher.replaceAll("").trim();
        partCode = partCode.replaceAll("  ", " ").replaceAll("  ", " ");
        partName = StringUtils.isEmpty(partName)?partName:partName.replaceAll("  ", "").trim();
        fitting.put("copyPartCode", partCode);
        fitting.put("copyPartName", partName);

        JSONArray parts = fitting.getJSONArray("parts");
        if (parts != null && parts.size() != 0) {
            parts.forEach(part -> {
                JSONObject partObj = (JSONObject)part;
                String copyPartCode = fitting.getString("copyPartCode");
                String copyPartName = fitting.getString("copyPartName");
                String pjmcId = partObj.getString("PJMCID");
                String pjmcMc = partObj.getString("PJMC");
                String iSPMC = "原厂" + pjmcMc + copyPartCode;
                List<Product> productList = productRepository.findAll(JpaDsl.toCriteriaByEq("name", iSPMC));
                    if (productList.size() != 0) {
                        Product product = productList.get(0);
                        String productId = product.getId();
                        if (!"0".equals(product.getState())) {
                            product.setState("0");
                            productRepository.save(product);
                        }

                        JSONObject listCondi = new JSONObject();
                        this.appendCondition(belongDept, saleDept, customerObj, jekunModelCode, vin, productId, pjmcId, pjmcMc, listCondi);
                        packageReturnData(returnDataArray, copyPartCode, copyPartName,
                                fitting.getBooleanValue("highLowconfig"),
                                fitting.getString("oldPartCode"),
                                isMatchParts, listCondi);
                    } else {
                        Category category = categoryRepository.findOne(pjmcId);
                        if (!StringUtils.isEmpty(category)) {
                            JSONObject productInfo = new JSONObject();
                            productInfo.put("SPMC", iSPMC);
                            if (category == null || category.getClassify() == null) {
                                throw new RuntimeException(pjmcMc + " 配件未找到对应品类！请联系数据中心定义");
                            }
                            productInfo.put("PLID", category.getClassify().getId());
                            productInfo.put("PLMC", category.getClassify().getName());
                            productInfo.put("PJMCID", pjmcId);
                            productInfo.put("PJMC", pjmcMc);
                            this.generateProduct(productInfo, copyPartCode, copyPartName,
                                    fitting.getBooleanValue("highLowconfig"),
                                    fitting.getString("oldPartCode"),
                                    belongDept, saleDept, customerObj, jekunModelCode, vin, isMatchParts, returnDataArray);
                        } else {
                            throw new RuntimeException("[" +pjmcId+ "]" + pjmcId + ", 此配件没有维护对应品类, 请先维护配件的品类再选择该配件");
                        }

                    }
            });
        } else {
            JSONObject productInfo = new JSONObject();
            String newPartName = partName.length() > 30?partName.substring(0, 30):partName;
            String iSPMC = "原厂" + newPartName + partCode;
            productInfo.put("SPMC", iSPMC);
            productInfo.put("PLID", "M01030501001");
            productInfo.put("PLMC", "待编译");
            productInfo.put("PJMCID", "013951");
            productInfo.put("PJMC", "待编译");
            this.generateProduct(productInfo, partCode, partName,
                    fitting.getBooleanValue("highLowconfig"),
                    fitting.getString("oldPartCode"),
                    belongDept, saleDept, customerObj, jekunModelCode, vin, isMatchParts, returnDataArray);
        }
    }

    private void packageReturnData(JSONArray returnDataArray, String copyPartCode, String copyPartName, boolean highLowconfig, String oldPartCode,
                                   boolean isMatchParts, JSONObject listCondi) {
        String topic = "event:serviceToForeign.appendJGInfo";
        if (Objects.equals("lossQuotation",sourceFrom)){
            topic = "event:fixedLossToForeign.appendItemInfo";
        }
        List singProductPrice = sendSynEvent(topic, listCondi);
        if (singProductPrice != null && singProductPrice.size() != 0) {
            if (!highLowconfig) {
                ((JSONObject) singProductPrice.get(0)).put("partCode", copyPartCode);
            } else {
                ((JSONObject) singProductPrice.get(0)).put("partCode", "E01");
                ((JSONObject) singProductPrice.get(0)).put("oldPartCode", oldPartCode);
            }
            ((JSONObject) singProductPrice.get(0)).put("partName", copyPartName);
            ((JSONObject) singProductPrice.get(0)).put("isMatchParts", isMatchParts);
            ((JSONObject) singProductPrice.get(0)).put("haveOffice", "暂无报价");
            returnDataArray.addAll(singProductPrice);
        }
    }

    private void generateProduct(JSONObject productData, String partCode, String partName,  boolean highLowconfig, String oldPartCode,  JSONObject belongDept, JSONObject saleDept, JSONObject customerObj, String jekunModelCode, String vin,
                                 boolean isMatchParts, JSONArray returnDataArray) {
        this.formatProduct(productData, partCode, new JSONObject());
        String productId = "";
        String topic = "event:piService.synTempoProduct";
        List singleInsertProduct = new ArrayList();
        try {
            singleInsertProduct = sendSynEvent(topic, productData);
        } catch (Exception e) {
            String message = e.getMessage();
            productId = getNumeric(message.substring(message.indexOf("：") + 1));
        }

        if (!singleInsertProduct.isEmpty()) {
            JSONObject singleInsertProductObj = (JSONObject) singleInsertProduct.get(0);
            if (singleInsertProductObj.getBoolean("success")) productId = singleInsertProductObj.getString("obj");
        }
        if (!StringUtils.isEmpty(productId)) {
            JSONObject listCondi = new JSONObject();
            String pjmcId = productData.getString("PJMCID");
            String pjmcMc = productData.getString("PJMC");
            this.appendCondition(belongDept, saleDept, customerObj, jekunModelCode, vin, productId, pjmcId, pjmcMc, listCondi);
            packageReturnData(returnDataArray,partCode,partName, highLowconfig, oldPartCode, isMatchParts, listCondi);
        }
    }

    private String generateProduct(JSONObject productData, String partCode, JSONObject product) {
        this.formatProduct(productData, partCode, product);
        if (!StringUtils.isEmpty(product.getString("standardType")) && ("Accumulator".equals(product.getString("standardType"))
                || "Tyre".equals(product.getString("standardType")))) {
            JSONArray array = new JSONArray();
            array.add(product.getJSONObject("extend"));
            productData.put("MAS_SPXXKZB", array);
        }
        String productId = "";
        String topic = "event:piService.synTempoProduct";
        List singleInsertProduct = new ArrayList();
        try {
            singleInsertProduct = sendSynEvent(topic, productData);
        } catch (Exception e) {
            String message = e.getMessage();
            productId = getNumeric(message.substring(message.indexOf("：") + 1));
        }

        if (!singleInsertProduct.isEmpty()) {
            JSONObject singleInsertProductObj = (JSONObject) singleInsertProduct.get(0);
            if (singleInsertProductObj.getBoolean("success")) productId = singleInsertProductObj.getString("obj");
        }
        return productId;
    }

    /**
     * 格式化商品到老框架
     * @param productData
     * @param partyCode
     */
    private void formatProduct(JSONObject productData, String partyCode, JSONObject copyProduct) {
        productData.put("PPID", Objects.isNull(copyProduct) || copyProduct.isEmpty()?"003676" : copyProduct.getJSONObject("spBrand").getString("id"));//品牌id
        productData.put("PPMC", Objects.isNull(copyProduct) || copyProduct.isEmpty()?"原厂" : copyProduct.getJSONObject("spBrand").getString("name"));//品牌名称
        productData.put("SPZID", "10");//商品组
        productData.put("SPZMC", "一般商品");//商品组
        productData.put("SPXH", partyCode);
        productData.put("OEMID", partyCode);
        productData.put("SSLBID", "J5");//
        productData.put("SSLBMC", "13%增值税");
        ServeCategory serviceCategory = SpringManager.getBean(ServeCategoryRepository.class).findOne(productData.getString("PLID"));
        if (!Objects.isNull(serviceCategory)) {
            productData.put("FWLXID", serviceCategory.getServeType().getId());
            productData.put("FWLXMC", serviceCategory.getServeType().getName());
        }
        productData.put("CZY", "admin");
        productData.put("CGZID", "0001");
        productData.put("CGZMC", "广州采购组");
        productData.put("VIPYELX", 0);
        productData.put("JEHSBJ", 1);
        productData.put("SPZCLX", 0);
        productData.put("SLHSBJ", 0);
        productData.put("XZWZBJ", 0);
        productData.put("FWSPBJ", 0);
        productData.put("MFHCBJ", 0);
        productData.put("JJHSBJ", 0);
        productData.put("TMGLBJ", 1);
        productData.put("DJSPBJ", 0);
        productData.put("KSFWBJ", 0);
        productData.put("CXZKBJ", 0);
        productData.put("BZQBJ", 0);
        productData.put("KZZCBJ", 0);
        productData.put("SPZT", 0);
        productData.put("SGFS", 1);
        productData.put("SB", 0);

        JSONObject uomData = new JSONObject();
        uomData.put("JLDWID", "001");
        uomData.put("JLDW", "件");
        uomData.put("YXBJ", 1);
        uomData.put("HSBL", 1);
        uomData.put("L", 0);
        uomData.put("W", 0);
        uomData.put("H", 0);
        uomData.put("TJ", 0);
        uomData.put("SPMZ", 0);
        uomData.put("SPJZ", 0);
        uomData.put("ZCMRBJ", 1);
        uomData.put("CGMRBJ", 1);
        uomData.put("XSMRBJ", 1);
        uomData.put("HYDWBJ", 1);
        JSONArray uomArray = new JSONArray();
        uomArray.add(uomData);
        productData.put("MAS_SPBZ", uomArray);
    }

    private void appendCondition(JSONObject belongDept, JSONObject saleDept, JSONObject customerObj, String jekunModelCode, String vin, String productId,
                                 String pjmcId, String pjmcMc, JSONObject listCondi) {
        // 拼接condition
        // 配件商品
        JSONObject fitting = new JSONObject();
        JSONObject common = new JSONObject();
        common.put("id", pjmcId);
        common.put("name", pjmcMc);
        fitting.put("fitting", common);

        common = new JSONObject();
        common.put("id", productId);
        listCondi.put("condition", fitting);
        listCondi.getJSONObject("condition").putAll(common);


        // 门店数据
        common = new JSONObject();
        common.put("belongDept", belongDept);
        common.put("saleDept", saleDept);
        listCondi.put("conditionModel", common);

        // 车辆数据
        JSONObject customerCar = new JSONObject();
        common = new JSONObject();
        common.put("vin", jekunModelCode);
        common.put("jekunModelCode", jekunModelCode);
        customerCar.put("customerCar", common);
        listCondi.getJSONObject("conditionModel").putAll(customerCar);

        // 会员数据
        JSONObject customer = new JSONObject();
        common = new JSONObject();
        common.put("level", customerObj.get("level"));
        common.put("userRole", customerObj.getJSONObject("userRole"));
        customer.put("customer", common);
        listCondi.getJSONObject("conditionModel").putAll(customer);
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<Product> findAll(SimpleRequest request) {
        return productRepository.findAll(PageRequest.of(request.get("page"), request.get("size")));
    }

    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Product product = productRepository.findOne(id);
        if (product == null) throw new RuntimeException("商品编码：" + request.get("id") + " 在系统中不存在。");
        productRepository.delete(product);
        return "删除成功！";
    }

    public Product findOne(String id) {
        return productRepository.findOne(id);
    }

    /**
     * 功能：下拉模糊查询使用
     *
     * @param request
     * @return
     */
    public Page<Product> find(SimpleRequest request) {
        String key = "";
        try {
            key = request.get("key");
            return productRepository.find(key, PageRequest.of(request.get("page"), request.get("size")));
        } catch (Exception e) {
            return productRepository.findAll(PageRequest.of(request.get("page"), request.get("size")));
        }

    }

    /**
     * 查询出商品及其计量单位
     * @param request
     * @return
     */
    public Page<Map> findProductAndUom(SimpleRequest request) {
        List<Map> condition = request.get("condition");
        Page<Product> products = productRepository.findAll(JpaDsl.toCriteria(condition), PageRequest.of(request.get("page"), request.get("size")));

        List resultlist = products.getContent().stream().map(product -> {
            Map mapped = MapUtil.mapped(product);
            mapped.put("uomItems", productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id",product.getId())));
            return mapped;
        }).collect(Collectors.toList());
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(request.get("page"), request.get("size"), sort);
        PageImpl<Map> result = new PageImpl<Map>(resultlist, pageable, products.getTotalElements());
        return result;
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<Product> findAllGS(SimpleRequest request) {
        List<Map> newCondition = getConditionMap(request);
        Page<Product> products =
                productRepository.findAll(
                        JpaDsl.toCriteria(newCondition), PageRequest.of(request.get("page"), request.get("size"))
                );
        PartyRole person = request.getPerson();
        products.getContent().forEach(product -> {
            StarProduct starProduct = starProductRepository.findByProductAndStarPerson(product, person);
            if (starProduct!=null)product.setStar(starProduct.isValid()?1:0);
        });
        return products;
    }

    private List<Map> getConditionMap(SimpleRequest request) {
        List<Map> condition = request.get("condition");
        List<Map> newCondition = new ArrayList<>();

        condition.forEach(obj ->{
            boolean target = true;
            Map map = new HashMap(obj);
            if("name".equals(map.get("field"))){
                obj.put("value", regexSplit((String)map.get("value")));
                target = condition.stream().noneMatch(m -> "product".equals(m.get("field")));
            }
            if ("product".equals(map.get("field"))){
                obj.put("field","id");
            }
            if ("id".equals(map.get("field"))){
                target = condition.stream().noneMatch(m -> "product".equals(m.get("field")));

            }
            if(target)newCondition.add(obj);
        });
        return newCondition;
    }

    public Page<Map> getProductComment(SimpleRequest request) {
        return productRepository.findClassifyComment(PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 输入： asc
     * 输出： a%s%c
     * @param str
     * @return
     */
    public String regexSplit(String str){
        String result = "";
        for(int i = 0;i<str.length();i++){
            if(i==0){
                result = result  + "%" + str.charAt(i) ;
            }else {
                result = result + "%" + str.charAt(i)  + "%";
            }
        }
        return result;
    }

    /**
     * 从字符串中提取纯数字
     * @param str
     * @return
     */
    public String getNumeric(String str) {
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }


    /**
     * 检测装配图的商品
     * @param simpleRequest
     */
    public void checkDwgProduct(SimpleRequest simpleRequest) {
        JSONArray returnDataArray = new JSONArray();
        JSONObject condition = simpleRequest.getJO();
        JSONArray fittlingArray = condition.getJSONArray("fitting");
        fittlingArray.forEach(fitting -> {
            JSONObject fittingObj = (JSONObject)fitting;
            boolean isMatchParts = fittingObj.getBooleanValue("isMatchParts");
            if (!fittingObj.getBooleanValue("isMatchParts")) {
                fittingObj.put("partName", "");
                fittingObj.put("oldPartCode", fittingObj.get("partCode"));
                fittingObj.put("partCode", "");
                returnDataArray.add(fittingObj);
                return;
            }

            String partCode = fittingObj.getString("partCode");
            String regEx = "[\\s~·`!！@#￥$%^……&*（()）\\-——\\-_=+【\\[\\]】｛{}｝\\|、\\\\；;：:‘'“”\"，,《<。.》>、/？?]";
            Pattern pattern = Pattern.compile(regEx);
            Matcher matcher = pattern.matcher(partCode);
            partCode = matcher.replaceAll("").trim();
            partCode = partCode.replaceAll("  ", " ").replaceAll("  ", " ");
            String partName = StringUtils.isEmpty(fittingObj.get("partName"))?"":fittingObj.getString("partName").replaceAll("  ", "").trim();
            fittingObj.put("copyPartCode", partCode);
            fittingObj.put("copyPartName", partName);

            JSONArray parts = fittingObj.getJSONArray("parts");
            if (parts != null && parts.size() != 0) {
                parts.forEach(part -> {
                    JSONObject partObj = (JSONObject)part;
                    String copyPartCode = fittingObj.getString("copyPartCode");
                    String pjmcId = partObj.getString("PJMCID");
                    String pjmcMc = partObj.getString("PJMC");
                    String iSPMC = "原厂" + pjmcMc + copyPartCode;
                    List<Product> productList = productRepository.findAll(JpaDsl.toCriteriaByEq("name", iSPMC));
                    if (productList.size() == 0) {
                        Category category = categoryRepository.findOne(pjmcId);
                        if (!StringUtils.isEmpty(category)) {
                            JSONObject productInfo = new JSONObject();
                            productInfo.put("SPMC", iSPMC);
                            if (category == null || category.getClassify() == null) {
                                throw new RuntimeException(pjmcMc + " 配件未找到对应品类！请联系数据中心定义");
                            }
                            productInfo.put("PLID", category.getClassify().getId());
                            productInfo.put("PLMC", category.getClassify().getName());
                            productInfo.put("PJMCID", pjmcId);
                            productInfo.put("PJMC", pjmcMc);
                            this.advanceGenerateProduct(productInfo, copyPartCode);
                        } else {
                            throw new RuntimeException("[" +pjmcId+ "]" + pjmcId + ", 此配件没有维护对应品类, 请先维护配件的品类再选择该配件");
                        }
                    }
                });
            } else {
                JSONObject productInfo = new JSONObject();
                Assert.isTrue(StringUtils.isEmpty(partName), "标准配件名称不能为空，请联系【数据中心对接人】处理！OE号：" + fittingObj.get("oldPartCode"));
                String newPartName = partName.length() > 30 ? partName.substring(0, 30):partName;
                String iSPMC = "原厂" + newPartName + partCode;
                productInfo.put("SPMC", iSPMC);
                productInfo.put("PLID", "M01030501001");
                productInfo.put("PLMC", "待编译");
                productInfo.put("PJMCID", "013951");
                productInfo.put("PJMC", "待编译");
                this.advanceGenerateProduct(productInfo, partCode);
            }

        });
    }


    private void advanceGenerateProduct(JSONObject productData, String partCode) {
        this.formatProduct(productData, partCode, new JSONObject());
        String productId = "";
        String topic = "event:piService.synTempoProduct";
        List singleInsertProduct = new ArrayList();
        try {
            singleInsertProduct = sendSynEvent(topic, productData);
        } catch (Exception e) {
            String message = e.getMessage();
            productId = getNumeric(message.substring(message.indexOf("：") + 1));
        }
    }

    public void synProductSPZT(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        outboxSubscriberService.commonSendRequest("local:productService.synProductSPZT", "product_spzt_syn", getJO);
    }

    @OutboxSubscriber(id="local:productService.synProductSPZT", name="商品信息状态同步")
    private void synSPXJD(OutboxPayloadWrapper outboxPayloadWrapper) {
        JSONObject resultObj = JSONObject.parseObject(outboxPayloadWrapper.getPayload());
        resultObj.forEach((k, v) -> {
            System.out.println(k);
            ((JSONArray) v).forEach(v1 -> {
                Product product = productRepository.findOne(v1.toString());
                product.setState(k);
                product.setValid(Integer.valueOf(k) == 0);
            });
        });
    }

    public Map findByNameAndIdAndCategory(SimpleRequest request){
        JSONObject requestJO = request.getJO();
        JSONArray condition = requestJO.getJSONArray("condition");

        //查询条件
        String name = null;
        String id = null;
        String category = null;
        for (Object o: condition) {
            JSONObject item = (JSONObject) o;
            if ("name".equals(item.getString("field"))){
                name = item.getString("value");
            }
            if ("id".equals(item.getString("field"))){
                id = item.getString("value");
            }
            if ("category".equals(item.getString("field"))){
                category = item.getString("value");
            }
        }

        //查询商品信息
        Page<Product> products = productRepository.findAll(JpaDsl.toCriteriaIgnoreNull("name", "LIKE", name,
                "id", "EQ", id,
                "category.name", "LIKE", category,
                "classify.id", "NOT_LIKE", "M0101",
                "state", "EQ", "0"), PageRequest.of(request.get("page"), request.get("size"), Sort.by(Sort.Direction.DESC, "id")));

        //页面字段
        List<Map> result = products.getContent().stream().map(product -> {
            Map map = new HashMap<>();
            map.put("id", product.getId());
            map.put("name", product.getName());
            map.put("brand", product.getBrand().getName());
            map.put("category", product.getCategory().getName());
            map.put("specification", product.getSpecifications());
            map.put("describe", product.getInstruction());
            map.put("ZBQ", getMonth(product.getBrand().getCharacter().getCode()));
            return map;
        }).collect(Collectors.toList());

        return MapUtil.mapper("content", result, "total", products.getTotalElements());
    }

    //根据品质获取质保期
    private int getMonth(String qualityId) {
        int month = 12;
        if ("001".equals(qualityId)){
            month = 3;
        }
        if ("004".equals(qualityId)){
            month = 1;
        }
        return month;
    }
}
